<template>
  <el-card class="book-card">
    <div class="card-content">
        <div class="book-prop">
          <div class="prop" :span="8">书籍名称</div>
          <div class="val" :span="16"><el-tag>{{ `《${book.name}》` }}</el-tag></div>
        </div>

        <div class="book-prop">
          <div class="prop">出版社</div>
          <div class="val">
            <el-tag type="info"> {{ book.publisher }}</el-tag>
          </div>
        </div>

        <div class="book-prop">
          <div class="prop">书籍编号</div>
          <div class="val"><el-tag type="info">{{ book?.identityKey ?? "暂无编号" }}</el-tag></div>
        </div>

        <div class="book-prop">
          <div class="prop">书籍位置</div>
          <div class="val"><el-tag>{{ getDepartmentName(book?.departmentId) }}</el-tag></div>
        </div>

      <div class="book-prop">
        <div class="prop">当前状态</div>
        <div class="val">
          <el-tag :type="BookStatusCache.getStatusStyle(book?.status)">{{ BookStatusCache.getStatusName(book?.status) }}</el-tag>
        </div>
      </div>
    </div>
    <div class="card-footer">
      <el-button type="success" @click="handleBorrowBook(book)" :disabled="book?.status > 0">借入</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import DepartmentCache from "~/store/system/departmentCache";
import { useApi } from "~/composeables";
import BookStatusCache from "~/store/booksvr/bookStatusCache";

const api = useApi();

const props = defineProps<{
  book: object,
  reload: Function,
}>();

const getDepartmentName = (depId: any) => {
  let match = DepartmentCache.departments.filter(x => x.id === depId);
  if (match?.length > 0) {
    return match[0]?.name;
  } else {
    return "/";
  }
};


const handleBorrowBook = (book: any) => {
  if(book.status > 0){
    ElMessageBox.alert("这本书已经借出！");
  }else{
    ElMessageBox.confirm("确定借入这本书吗？", "确定吗？", {confirmButtonText:"确定借入", cancelButtonText: "先不借了"})
      .then(() => {
        api.bookBookApi.borrow(book.id)
          .then(res => {
            if (res.success) {
              if(props.reload){
                props.reload();
              }
              ElMessageBox.alert("已成功借阅本书!")
            }else{
              ElMessageBox.alert("借阅失败，请联系管理员！");
            }
          });
      })
      .catch(err => {
        ElMessage.info("已取消借阅");
      });
  }
};

</script>

<style scoped>
.book-card{
  width: 360px;
  height: 200px;
  padding:10px;
  margin: 8px;
}

.card-content {
  margin: 0;
  padding: 0px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
}

.book-prop{
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 30px;
}

.prop{
  display: flex;
  justify-content: flex-start;
  width: 100px;
}

.val{
  font-size: 0.9em;
  color: #666;
}

.card-footer{
  height: 45px;
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}
</style>